package com.may._1;

/**
 * 多线程下的单例模式
 */
public class SingletonDemo {
    //多线程下为了性能，jvm会优化进行指令重排。加 volatile 禁止指令重排
    private static volatile SingletonDemo instance = null;

    private SingletonDemo(){
        System.out.println(Thread.currentThread().getName()+"\t 我是构造方法");
    }

    // DCL (Double Check Lock 双端检锁机制)，高并发情况下使用
    public static SingletonDemo getInstance(){
        if (instance == null){
            synchronized (SingletonDemo.class){
                if (instance == null){
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                    SingletonDemo.getInstance();
            },String.valueOf(i)).start();

        }
    }
}
